package ido.com.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 
 * @author ido green
 * http://idojava.blogspot.com 
 * 
 */
public class FileUtil {

    public static final String DATA_DIR = System.getProperty("user.home") + "/tcc/";
    public static final String DELIMITER = ",";
    public static final String SEMI_COL = ";";
    public static FileUtil sharedInstance = new FileUtil();
    private Properties properties = new Properties();

    private FileUtil() {
        readProp();
        if (!new File(DATA_DIR).exists()) {
            // create our app dir
            new File(DATA_DIR).mkdir();
        }
    }

    public void setProperty(String propName, String propVal) {
        properties.setProperty(propName, propVal);
    }

    public String getProperty(String key) {
        return properties.getProperty(key);
    }
    public String getProperty(String key, String def) {
        return properties.getProperty(key, def);
    }

    /**
     * Read properties file.
     */
    public void readProp() {
        try {
            properties.load(new FileInputStream(DATA_DIR + "gcal.prop"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void saveProp() {
        try {
            properties.store(new FileOutputStream(DATA_DIR + "gcal.prop"), null);
        } catch (Exception ex) {
            Logger.getLogger(FileUtil.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public ArrayList<String> readEmailsFile(String filename) {
        BufferedReader in;
        ArrayList<String> links = new ArrayList<String>();
        String str;
        try {
            in = new BufferedReader(new FileReader(DATA_DIR + filename));
            while ((str = in.readLine()) != null) {
                links.add(str);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return links;
    }

    /**
     * 
     * @param filename
     * @return
     */
    public String readTextFile(String filename) throws Exception {
        StringBuffer allContent = new StringBuffer("");
        String str;
        BufferedReader in = new BufferedReader(new FileReader(DATA_DIR + filename));
        while ((str = in.readLine()) != null) {
            allContent.append(str);
            allContent.append(DELIMITER);
        }
        in.close();
        return allContent.toString();
    }

    public void deleteLocalPipeData() {
        File dir = new File(FileUtil.DATA_DIR);
        String[] fileNames = dir.list();
        if (fileNames == null) {
            return;
        }
        for (int i = 0; i < fileNames.length; i++) {
            if (fileNames[i].indexOf("id=") > -1) {
                boolean removeIt = new File(fileNames[i]).renameTo(new File(
                        "old" + fileNames[i].substring(3)));
                System.out.println("rename it? file: " + removeIt);
            }
        }
    }

    /**
     * 
     * @param str
     * @return
     */
    private String checkReplaceAll(String str) {
        if (str != null && str.length() > 0) {
            str.replaceAll(SEMI_COL, DELIMITER);
        }
        return str;
    }

    public String convertUrlToFileName(String urlStr) {
        String tmpUrl = urlStr.substring(29, urlStr.length() - 5);
        return tmpUrl.replaceAll("/", "-");

    }

    /**
     * 
     * @param fileName
     * @param data
     * @throws Exception
     */
    public void writeToFile(String fileName, ArrayList<String> data)
            throws Exception {
        String fullFileName = DATA_DIR + fileName;
        System.out.println("-- The links are stored at: " + fullFileName);
        BufferedWriter out = new BufferedWriter(new FileWriter(fullFileName));

        for (Iterator it = data.iterator(); it.hasNext();) {
            String elem = (String) it.next();
            out.write(elem + "\n");
        }
        out.close();
    }

    /**
     *   // Get a Channel for the source file
    File f = new File("Replacement.java");
    FileInputStream fis = new FileInputStream(f);
    FileChannel fc = fis.getChannel();
    // Get a CharBuffer from the source file
    ByteBuffer bb = 
    fc.map(FileChannel.MAP_RO, 0, (int)fc.size());
    Charset cs = Charset.forName("8859_1");
    CharsetDecoder cd = cs.newDecoder();
    CharBuffer cb = cd.decode(bb);
     */
    /**
     * 
     * @param fileName
     * @param data
     */
    public void writeToFile(String fileName, String data) {
        try {
            BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
            out.write(data + "\n");
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String replceComma(String str) {
        if (str != null && str.length() > 0) {
            // re.replace('<.*?>', '', html)
            String patternStr = "<.*?>";
            String replaceStr = "";
            Pattern pattern = Pattern.compile(patternStr);
            Matcher matcher = pattern.matcher(str);
            str = matcher.replaceAll(replaceStr);
            str = str.replaceAll(DELIMITER, SEMI_COL);
            str = str.replaceAll("\n", "");
            return str;
        }
        return "N/A";
    }

    /**
     * @param urlStr
     */
    public String getResults(String urlStr) {
        String results = "";
        try {
            URL url = new URL(urlStr);
            // Read all the text returned by the server
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String str;
            StringBuffer sb = new StringBuffer();
            while ((str = in.readLine()) != null) {
                sb.append(str);
            }
            in.close();
            results = sb.toString();
        // System.out.println("++ our results page: "+ results);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return results;
    }

    /**
     * 
     * @param fileName
     * @param record -
     *            a string with , as dilimiter
     * @throws Exception
     */
    public synchronized void writeToCSVFile(String fileName, String record)
            throws Exception {
        fileName = DATA_DIR + fileName;
        System.out.println("Write info to our local db at: " + fileName);
        boolean append = new File(fileName).exists();
        FileOutputStream fos = new FileOutputStream(fileName, append);
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos,
                "UTF8"));
        out.write(record);
        out.newLine();
        out.close();
    }
}
